<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 顶部搜索 -->
        <div class="top">
          <el-row type="flex" justify="space-between">
            <el-col>
              <el-button type="primary" size="small" @click="isShowDialog = true">添加客户</el-button>
            </el-col>
            <el-col>
              <el-row type="flex">
                <!-- 经纪下拉选择框 -->
                <el-select v-model="agentsList" style="width: 150px" filterable placeholder="请选择" size="small" @change="agentChange">
                  <el-option
                    v-for="item in agentOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <!-- 搜索框 -->
                <el-input v-model="searchContent" placeholder="请输入内容" style="width:100%" size="small" />
                <!-- 筛选按钮 -->
                <el-button size="small" @click="searchList">筛选</el-button>
              </el-row>
            </el-col>
          </el-row>
        </div>
        <!-- 表格 -->
        <el-table border class="bottom" :data="clientList">
          <el-table-column label="图片">
            <template #default="{row}">
              <img :src="row.image" alt="" class="images">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="邮箱" prop="email" />
          <el-table-column label="电话" prop="phone" />
          <el-table-column label="经纪" prop="agent.name" />
          <el-table-column label="微信" prop="wechat" />
          <el-table-column label="介绍" prop="desc" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button size="small" type="primary" @click="edit(row.id)">编辑</el-button>
              <el-button size="small" type="danger" @click="delClient(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 新增对话框 -->
        <el-dialog :visible="isShowDialog" title="新增客户" @close="btnCancel">
          <el-form ref="addClient" :model="formData" :rules="rules">
            <el-form-item v-if="formData.id" label="经纪" prop="agent">
              <el-select v-model="formData.agent.id">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-else label="经纪" prop="agent">
              <el-select v-model="formData.agent">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入名称" style="width:90%" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" style="width:90%" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入电话" style="width:90%" />
            </el-form-item>
            <el-form-item label="微信" prop="wechat">
              <el-input v-model="formData.wechat" placeholder="请输入微信" style="width:90%" />
            </el-form-item>
            <el-form-item label="概述" prop="desc">
              <el-input v-model="formData.desc" placeholder="请输入概述" style="width:90%" />
            </el-form-item>
            <el-form-item label="封面">
              <UploadImage ref="imgUrl" @imgUrl="imgUrlFn" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button type="primary" @click="addClients">确定</el-button>
            <el-button @click="btnCancel">取消</el-button>
          </template>
        </el-dialog>
        <!-- 分页 -->
        <el-row type="flex" justify="center" class="pages">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSetting._limit"
            :current-page="currentPage"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入接口
import { getAgentsList } from '@/api/agents'
import { getClientList, putClients, addClient, putClient, delClients, allClientList } from '@/api/client'
import UploadImage from '@/views/agents/components/UploadImage.vue'
export default {
  components: { UploadImage },
  data() {
    return {
      searchContent: '',
      total: 0, // 总条数
      currentPage: 0,
      pageSetting: {
        _limit: 2,
        _start: 0
      }, // 最大条数
      formData: {
        agent: '',
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '',
        image: ''
      }, // 表单数据
      isShowDialog: false, // 控制对话框显示隐藏
      agentsList: [], // 经纪下拉数据
      agentOptions: [], // 经纪下拉
      options: [], // 经纪下拉
      clientList: [], // 客户列表数据
      rules: {
        agent: [{ required: true, message: '请选择经纪', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }, {
          pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱格式不正确', trigger: 'blur'
        }],
        phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, {
          pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'
        }],

        wechat: [{ required: true, message: '微信号不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '概述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getClientList()
    this.getAgentsList()
  },
  methods: {
    // 获取经纪数据
    async getAgentsList() {
      const { data } = await getAgentsList()
      this.options = data
      this.agentOptions = data
    },
    // 获取客户列表数据
    async getClientList() {
      const { data } = await getClientList(this.pageSetting)
      const length = await allClientList()
      this.total = length.data
      this.clientList = data
    },
    // 编辑功能
    async edit(id) {
      const { data } = await putClients(id)
      this.formData = data
      this.$nextTick(() => {
        this.$refs.imgUrl.fileList = [
          { url: data.image }
        ]
      })
      this.isShowDialog = true
    },
    // 删除客户
    async delClient(id) {
      await this.$confirm('确定要删除嘛?')
      await delClients(id)
      this.$message.success('操作成功')
      this.getClientList()
    },
    // 关闭弹窗
    btnCancel() {
      this.formData = {
        agent: '',
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '',
        image: ''
      }
      this.$refs.imgUrl.fileList = []
      this.isShowDialog = false
      this.$refs.addClient.resetFields()
    },
    // 新增
    async addClients() {
      try {
        // 校验表单
        await this.$refs.addClient.validate()
        // 判断是否有id
        if (this.formData.id) {
          await putClient(this.formData)
          // 提示用户
          this.$message.success('编辑成功')
        } else {
          // 调用新增接口
          await addClient(this.formData)
          // 提示用户
          this.$message.success('新增成功')
        }
        // 关闭对话框
        this.isShowDialog = false
        // 更新页面
        this.getClientList()
        this.$refs.addClient.resetFields()
      } catch (error) {
        console.log(error)
      }
    },
    imgUrlFn(url) {
      this.formData.image = url
    },
    // 分页
    async changePage(newPage) {
      // 判断是否有agentsList
      if (this.agentsList) {
        const start = (newPage - 1) * this.pageSetting._limit
        const res = await getClientList({ _limit: this.pageSetting._limit, agent: this.agentsList, _start: start })
        this.clientList = res.data
        this.currentPage = 1
        return
      }
      // 判断是否有agentsList
      if (this.searchContent) {
        const start = (newPage - 1) * this.pageSetting._limit
        const { data } = await getClientList({ _limit: this.pageSetting._limit, name_contains: this.searchContent, _start: start })
        this.clientList = data
        this.currentPage = 1
        return
      }
      this.pageSetting._start = (newPage - 1) * this.pageSetting._limit
      const { data } = await getClientList(this.pageSetting)
      this.clientList = data
      this.currentPage = 1
    },
    // 下拉选中时触发
    async agentChange() {
      const res = await getClientList({ _limit: this.pageSetting._limit, agent: this.agentsList })
      this.clientList = res.data
      const length = await allClientList({ agent: this.agentsList })
      this.total = length.data
      this.currentPage = 1
      this.searchContent = ''
    },
    async searchList() {
      if (this.searchContent) {
        const { data } = await getClientList({ _limit: this.pageSetting._limit, name_contains: this.searchContent })
        this.clientList = data
        const length = await allClientList({ name_contains: this.searchContent })
        this.total = length.data
        this.currentPage = 1
        this.agentsList = ''
      } else {
        await this.getClientList()
        this.currentPage = 1
        this.agentsList = ''
      }
    }
  }
}
</script>

<style>
.top{
  padding-bottom: 20px;
  border-bottom: 1px solid #ddd;
}
.bottom{
  margin-top: 20px;
}
.images{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}
.pages{
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ddd;
}
</style>
